package son.niit.ict;

import android.app.Activity;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

public class SplashScreen extends Activity implements Runnable {

	Thread threadsplash;
	String TAG = "Test";
	ImageView background;
	boolean active = true;
	long timestart = 1000;

	//
	SoundPool soundpool;
	int soundplay;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// khai bao khong su dung tieu de
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// yeu cau man hinh giao dien rong kin man hinh dien thoai
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		// thiet lap man hinh giao dien la the hien qua file thiet ke layout splashscreen
		setContentView(R.layout.splahscreen);

		// khai bao cai anh nen logo
		background = (ImageView) findViewById(R.id.logo);
		background.setBackgroundResource(R.drawable.splash);
		
		// bien nay bang true de noi len ko co hanh dong tac dong len man hinh luc no dang quang cao logo
		active = true;

		// khai bao doi tuong de play 1 file am thanh.
		soundpool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
		soundplay = soundpool.load(this, R.raw.intro, 1);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	// ham nay duoc goi khi man hinh dien thoai sang, duoc goi sau ham onResume()
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		// neu hien tai ko co tuyen nao chay thi se khoi tao thread moi de chay qua trinh gioi thieu logo
		if (threadsplash == null) {
			threadsplash = new Thread(this);
			threadsplash.start();
		}
		super.onWindowFocusChanged(hasFocus);
	}

	// phuong thuc nay duoc goi ngay khi thread chay
	@Override
	public void run() {
        // thuc hien cac lenh trong khoi try
		try {
			while (active && (timestart >= 0)) {
				// active=true, neu ko co ai cham tay vao man hinh va thoi gian muon quang cao chua het thi cu chay thread de bat am thanh neu co loi xay ra se thuc hien khoi lenh trong catch
				// neu het thoi gian hoac co su kien cham tayvao man hinh thi se thoat va thuc hien khoi lenh trong finally(do la bat len activity Mainmenu)
				timestart -= 20;
				soundpool.play(soundplay, 0f, 1f, 0, 0, 1.5f);
				Thread.sleep(100);
			}

		} catch (InterruptedException e) {
			// TODO: handle exception
		} finally {
			startActivity(new Intent(getApplicationContext(),MainMenu.class));
			finish();
		}
	}

	// ham nay de xu li khi co su kien cham tay vao man hinh,
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			active = false;
		}
		return super.onTouchEvent(event);
	}
}